<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="产品名称">
        <el-select
          v-model="queryParams.productId"
          clearable
          :filter-method="hospitalFilter"
          filterable
          placeholder="请选择产品名称"
          class="!w-240px"
        >
          <el-option
            v-for="item in supplierList"
            :key="item.id"
            :label="item.name + ' ' + item.standard"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="有效期" prop="productValidityDate">
        <el-date-picker
          v-model="queryParams.productValidityDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <!-- <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:sec-stock:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button> -->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <!-- <el-table-column label="编号" align="center" prop="id" /> -->
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="产品规格" align="center" prop="productStandards" />
      <el-table-column label="产品单位" align="center" prop="productUnit" />
      <el-table-column label="生产批次" align="center" prop="productBatch" />
      <el-table-column label="入库批次" align="center" prop="inboundBatch" />
      <!-- <el-table-column label="产品单价" align="center" prop="productPrice" /> -->
      <el-table-column label="库存数量" align="center" prop="count" />
      <el-table-column
        label="有效期"
        align="center"
        prop="productValidityDate"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="预警效期" align="center" prop="expiryDate" width="180px" />
      
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <SecStockForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { SecStockApi, SecStockVO } from '@/api/erp/secstock'
import SecStockForm from './SecStockFormExPiry.vue'
import { now } from 'lodash-es'
import debounce from 'lodash/debounce'
import { defaultProps, handleTree } from '@/utils/tree'
import { ProductApi, ProductVO } from '@/api/spd/product/product'
const productList = ref<SecStockVO[]>([]) // 产品列表
const supplierList = ref<ProductVO[]>([])  // 供应商列表

/** ERP 二级库库存 列表 */
defineOptions({ name: 'SecStock' })

var deptId2: undefined
onMounted(() => {
  const Info = JSON.parse(localStorage.getItem('user') || '{}');
  const userInfo = JSON.parse(Info.v)
  deptId2 = userInfo.user.deptId
  
});

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<SecStockVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  warehouseId: undefined,
  deptId: deptId2,
  prodictName: undefined,
  productId: undefined,
  productUnit: undefined,
  productStandards: undefined,
  productPrice: undefined,
  productBatch: undefined,
  productValidityDate: [],
  count: undefined,
  creator: undefined,
  createTime: [],
  queryType : 2
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    queryParams.deptId = deptId2
    queryParams.queryType = 2
    const data = await SecStockApi.getSecStockPageByDetain(queryParams)
    data.list.forEach((item) => {
      var expir = Math.trunc((item.productValidityDate-now())/(1000*60*60*24))
      if(expir > 0){
        item.expiryDate = '不足' + expir + '天'
      }else{
        item.expiryDate = '已过期'
      }
    })
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/**
 * 键入监听方法
 */
const hospitalFilter = async(params)=> {
  //判断键入是否有值
  if(params!==""){
    //有值调用防抖方法
    debouncedSearch(params)
  }else{
    //没有键入值，集合为空
    const ids = await SecStockApi.getIds(Number(deptId2));
    const data = await ProductApi.getProductSimpleListByIds(params,ids)
    supplierList.value = data
  }
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  // 手动重置 queryParams
  Object.assign(queryParams, {
    pageNo: 1,
    pageSize: 10,
    warehouseId: undefined,
    deptId: deptId2,
    productId: undefined,
    productName: undefined,
    productUnit: undefined,
    productStandards: undefined,
    productPrice: undefined,
    productBatch: undefined,
    productValidityDate: [],
    count: undefined,
    creator: undefined,
    createTime: [],
    queryType: 3
  })
  // 清空 el-select 的过滤条件
  queryParams.productName = undefined
  handleQuery()
}

/**
 * 根据键入的值查询产品列表
 */
const productLists=async(params)=>{
  // 加载产品列表
  const ids = await SecStockApi.getIds(Number(deptId2));
  const supplierData = await ProductApi.getProductSimpleListByIds(params,ids)
  supplierList.value = handleTree(supplierData, 'id')
}

// 创建一个防抖函数来处理搜索操作
 const debouncedSearch =debounce((params,delay = 500) => { 
      //定义等待时间
      const timer = ref() 
      // 模拟异步数据获取（例如API调用）
      if(timer.value){
          //清除等待时间
          clearTimeout(timer.value); 
        }
      //等待时间赋值
      timer.value = setTimeout(async() => {
        //调用后端根据键入的值查询产品列表方法
        productLists(params)
      }, delay); // 延迟500毫秒以模拟网络延迟或数据处理时间
  }, 500); // 防抖等待时间为500毫秒   

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await SecStockApi.deleteSecStock(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await SecStockApi.exportSecStock(queryParams)
    download.excel(data, 'ERP 二级库库存.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(async () => {
  getList()
  // const data = await SecStockApi.getProductIds(Number(deptId2))
  // productList.value = data
})
</script>